//
//  NewRegisterViewController.m
//  visi_register
//
//  Created by Tai Truong on 11/15/12.
//  Copyright (c) 2012 Tai Truong. All rights reserved.
//

#import "RegisterViewController.h"
#import "AppViewController.h"
#import "Define.h"
#import "JSON.h"
#import "UserDataManager.h"

typedef enum {
    enumTagInvalid,
    enumTagEmailAlert
}enunTag;

typedef enum
{
    ENUM_FIELD_CHECK_FIRST_NAME,
    ENUM_FIELD_CHECK_LAST_NAME,
    ENUM_FIELD_CHECK_USER_NAME,
    ENUM_FIELD_CHECK_EMAIL,
    ENUM_FIELD_CHECK_PASSWORK,
    ENUM_FIELD_CHECK_FIELD_EMPTY,
    ENUM_FIELD_CHECK_INVATION_CODE
}ENUM_FIELD_CHECK;

@implementation RegisterViewController
{
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _APIRequester = [[APIRequester alloc] init];
    
    _textFieldUsername.font = [UIFont fontWithName:FONT_APP_THIN size:20];
    _textFieldPassword.font = [UIFont fontWithName:FONT_APP_THIN size:20];
    _textFieldEmail.font = [UIFont fontWithName:FONT_APP_THIN size:20];
    _textFieldFirstName.font = [UIFont fontWithName:FONT_APP_THIN size:20];
    _textFieldLastName.font = [UIFont fontWithName:FONT_APP_THIN size:20];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    self.textFieldEmail = nil;
    self.textFieldUsername = nil;
    self.textFieldPassword = nil;
    self.textFieldFirstName = nil;
    self.textFieldLastName = nil;
    [self setControlMainScreen:nil];
    [self setScrollViewMainView:nil];
    [super viewDidUnload];
}

#pragma mark - UIButton Actions

- (IBAction)backBtnTouchUpInside:(UIButton *)sender {
    [[AppViewController Shared] changeBackFromRegister];
}

- (IBAction)termBtnTouchUpInside:(UIButton *)sender {
    CGRect rect = self.termsView.frame;
    rect.origin.y = HEIGHT_IPHONE;
    [UIView animateWithDuration:0.3f animations:^{
        self.termsView.frame = rect;
    }
                     completion:^(BOOL finished) {
                         [self.termsView removeFromSuperview];
                     }
     ];
}

- (IBAction)termOfServiceTouchUpInside:(UIButton *)sender {
    NSLog(@"termOfServiceTouchUpInside");
    [self.termsView setHidden:NO];
    [_termConditionWebView loadHTMLString:@"<html><head><title> Term & Codition </title></head> <body><div class=\"Terms-Conditions\"><h1 style=\"text-align:center;\">Aigo Terms &amp; Conditions</h1>     <p>     You agree that by registering on Aigo, by using our mobile application or our website or accessing other information provided as part of the Aigo services (collectively “Aigo” or the “Services”), you are entering into a legally binding agreement with Aigo, Inc., having its principal office located at 2839 Paces Ferry Road, Suite 1100, Atlanta, Georgia 30339 USA.  If you reside in the United States (“we,” “us,” “our,” and “Aigo”) based on Aigo’s Terms &amp; Conditions and the Aigo Privacy Policy, which is incorporated herein by reference (collectively referred to as the “Agreement”) and become a Aigo user (“User”).     </p>     <p>     If you are using Aigo on behalf of a company or other legal entity, you are individually bound by this Agreement even if your company has a separate agreement with us. If you do not want to register an account and become a Aigo User, stop here, do NOT click “register” and do not access, view, download or otherwise use any Aigo application, webpage, information or services. By clicking “register” you acknowledge that you are at least 13 years of age and have read and understood the terms and conditions of this Agreement and that you agree to be bound by all of its provisions. Please note that the Aigo Terms &amp; Conditions and Privacy Policy are also collectively referred to as Aigo’s “User Agreement.”     </p>     <h3> USER OBLIGATIONS.</h3>     <ul class=\"number-buidlet\">     <li>     <p>     1.  You must comply with all applicable laws, the Agreement, as may be amended from time to time with or without advance notice, and the policies and processes explained in the following sections:     </p>     <ul class=\"alphabe-buidlet\">     <li>     a) DOs and DON’Ts;     </li>     <li>     b) Complaints Regarding Content Posted; and     </li>     <li>     c) Aigo’s Privacy Policy.     </li>     </ul>          </li>     <li>     <p>	2.  You own the information you provide Aigo under this Agreement, and may delete such content at any time, unless you have shared information or content with others and they have not deleted it, or it was copied or stored by other users. Additionally, you grant Aigo a nonexclusive, irrevocable, worldwide, perpetual, unlimited, assignable, sublicenseable, fully paid up and royalty-free right to us to copy, prepare derivative works of, improve, distribute, publish, remove, retain, add, process, analyze, use and commercialize, in any way now known or in the future discovered, any information you provide, directly or indirectly to Aigo, including, but not limited to, any user generated content, ideas, concepts, techniques or data to the services, you submit to Aigo, without any further consent, notice and/or compensation to you or to any third parties.     </p>     <p>     By uploading information on our mobile application, or WebPages, you represent and warrant that you are entitled to submit the information and that the information is accurate, not confidential, and not in violation of any contractual restrictions or other third party rights. It is your responsibility to keep your Aigo profile information accurate and updated.     </p>     </li>     <li>     <h3>3. Eligibility.</h3>     <p>     To be eligible to use the Service, you must meet the following criteria and represent and warrant that you: (1) are 13 years of age or older; (2) are not currently restricted from the Services, or not otherwise prohibited from having a Aigo account, (3) are not a competitor of Aigo or are not using the Services for reasons that are in competition with Aigo; (4) have full power and authority to enter into this Agreement and doing so will not violate any other agreement to which you are a party; (5) will not violate any rights of Aigo, including intellectual property rights such as copyright or trademark rights.     </p>     </li>     <li>     <h3>4. Log-In</h3>     <p>     You agree to: (1) Keep your password secure and confidential; (2) not permit others to use your account; (3) refrain from using other Users’ accounts; (4) you are responsible for anything that happens through your account until you close down your account or show written proof that your account security was compromised due to no fault of your own.     </p>     </li>     <li>     <h3>5. Indemnification.</h3>     <p>You indemnify Aigo and hold Aigo harmless for all damages, losses and costs (including, but not limited to, reasonable attorneys’ fees and costs) related to all third party claims, charges, and investigations, caused by (1) your failure to comply with this Agreement, including, without limitation, your submission of content that violates third party rights or applicable laws, (2) any content you submit to the Services, and (3) any activity in which you engage on or through Aigo. </p>     </li>     <li>     <h3>6. Aigo Applications.</h3>     <p>Aigo may offer the Services through applications built using Aigo’s platform (“Aigo Applications”). Examples of Aigo Applications include its smart phone applications (Aigo for iPhone, Android, or Blackberry), and Aigo’s “Share” buttons and other interactive plug-in distributed on websites across the web. Aigo Applications are distinct from third party Platform Applications, you agree that information about you and your use of the Services, including, but not limited to, your device, your mobile carrier, your internet access provider, your physical location, and/or web pages containing Aigo plug-in that load in your browser may be communicated to us. </p>     <p>     You also agree that by importing any data through the Aigo Application, you represent that you have authority to share the transferred data with your mobile carrier or other access provider. In the event you change or deactivate your mobile account, you must promptly update your Aigo account information to ensure that your messages are not sent to the person that acquires your old number and failure to do so is your responsibility. You acknowledge you are responsible for all charges and necessary permissions related to accessing Aigo through your mobile access provider. Therefore, you should check with your provider to find out if the Services are available and the terms for these services for your specific mobile devices as well as any data usage fees.     </p>     <p>     Finally, by using any downloadable application to enable your use of the Services, you are explicitly confirming your acceptance of the terms of the End User License Agreement associated with the application provided at download or installation, or as may be updated from time to time.     </p>     </li>     <li>     <h3>7. Kards, Trading, Sharing, Konnect, Deals</h3>     <p>     Aigo offers various environments such as My Kards, Konnect, Deals where you may share or trade your Kards, post comments, find deals or Konnect with others. Aigo also enables sharing of information by allowing users to post updates and other content to their profile and other areas of its sites, such as Aigo Konnect and MyKards as well as Aigo WebPages. </p>     <p>     Please note that information you share may be seen and used by other Users, and Aigo cannot guarantee that other Users will not use the information that you share on Aigo. Therefore, if you have information that you would like to keep confidential and/or don’t want others to use, make certain that you select the “visible”  “off” settings within the application or webpage. Kards that you have shared with other users in the past will have access to any new information that you post to them.          </p>          </li>     <li>     <h3>8. Privacy.</h3>     <p>     Our Privacy Policy is incorporated herein and your acceptance to “register” as a Aigo user is your   agreement to such Privacy Policy and governs our treatment of any information, including personally identifiable information you submit to us. Please note that certain information, statements, data, and content (such as photographs) which you may upload or submit to Aigo are likely to, reveal your gender, ethnic origin, nationality, age, and/or other personal information about you. You acknowledge that your submission of any information, statements, data, and content to us is voluntary on your part.     </p>     </li>     <li>     <h3>9. Idea Submissions to Aigo</h3>     <p>     By submitting ideas, suggestions, documents, and/or proposals (\"Submissions\") to you acknowledge and agree that: (a) your Contributions do not contain confidential or proprietary information; (b) Aigo is not under any obligation of confidentiality, express or implied, with respect to the Contributions; (c) Aigo shall be entitled to use or disclose (or choose not to use or disclose) such Contributions for any purpose, in any way, in any media worldwide; (d) Aigo may have something similar to the Contributions already under consideration or in development; (e) you irrevocably assign to Aigo all rights to your Contributions; and (f) you are not entitled to any compensation or reimbursement of any kind from Aigo under any circumstances.     </p>     </li>     <li>     <h3> 10. YOUR RIGHTS.</h3>     <p>     On the condition that you comply with all your obligations under this Agreement, including, but not limited to, the Do’s and Don’ts listed in Section 22, we grant you a limited, revocable, nonexclusive, nonassignable, nonsublicenseable license and right to access the Services, through a generally available mobile device web browser,  or application (but not through automated tools such as: scraping, spidering, crawling or other technology or software used to access data without the express written consent of Aigo or its Users), view information and use the Services that we provide on Aigo’s application, and/or WebPages and in accordance with this Agreement. Any other use of Aigo contrary to our mission and purpose (such as seeking to connect to someone you do not know or trust, or to use information gathered from Aigo commercially unless expressly authorized by Aigo) is strictly prohibited and a violation of this Agreement. We reserve all rights not expressly granted in this Agreement, including, without limitation, title, ownership, intellectual property rights, and all other rights and interest in Aigo and all related items, including any and all copies made of the Aigo products.     </p>     </li>     <li>     <h3>11. OUR RIGHTS AND OBLIGATIONS.</h3>     <p>     Services - For as long as Aigo continues to offer its platform, Aigo shall provide and seek to update, improve and expand its services. As a result, we allow you to access Aigo as it may exist and be available on any given day and have no other obligations, except as expressly stated in this Agreement. We may modify, replace, refuse access to, suspend or discontinue Aigo, partially or entirely, or change and modify prices for all or part of the Services for you or for all our users in our sole discretion. All of these changes shall be effective upon an application update or upon their posting on our sites or by direct communication to you unless otherwise noted. Aigo further reserves the right to withhold, remove and or discard any content available as part of your account, with or without notice if deemed by Aigo to be contrary to this Agreement. For avoidance of doubt, Aigo has no obligation to store, maintain or provide you a copy of any content that you or other Users provide when using the Services.     </p>     </li>     <li>     <h3>12. Third Party Sites  </h3>     <p>     Aigo may include links to third party sites (“Third Party Sites”) on our mobile app or on Aigo WebPages (www.Aigo.com). Aigo also enables third party developers (“Platform Developers”) to create applications (“Platform Applications”) that provide features and functionality using data and developer tools made available by Aigo through its developer platform.     </p>     <p>     You are responsible for evaluating whether you want to access or use a Third Party Site or Platform Application. You should review any applicable terms and/or privacy policy of a Third Party Site or Platform Application before using it or sharing any information with it, because you may give the operator permission to use your information in ways we would not.     </p>     <p>     Aigo is not responsible for, and does not endorse, any features, content, advertising, products or other materials on or available from Third Party Sites or Platform Applications. Aigo also does not screen, audit, or endorse Platform Applications. Accordingly, if you decide to access Third Party Sites or use Platform Applications, you do so at your own risk and agree that your use of any Platform Application is on an “as-is” basis without any warranty as to the Platform Developer’s actions, and that this Agreement does not apply to your use of any Third Party Site or Developer Application.     </p>     <p>     Please note: If you allow a Platform Application or Third Party Site to authenticate to or connect with your Aigo account, that application or website can access information on Aigo related to you and your connections.     </p>     </li>     <li>     <h3>13. Disclosure of User Information.</h3>     <p>     You acknowledge, consent and agree that we may access, preserve, and disclose your registration and any other information you provide if required to do so by law or in a good faith belief that such access preservation or disclosure is reasonably necessary in our opinion to: (1) comply with legal process, including, but not limited to, civil and criminal subpoenas, court orders or other compulsory disclosures; (2) enforce this Agreement; (3) respond to claims of a violation of the rights of third parties, whether or not the third party is a User, individual, or government agency; (4) respond to customer service inquiries; or (5) protect the rights, property, or personalsafety of Aigo, our Users or the public.     </p>     </li>     <li>     <h3>14. Konnect, Trades, Interactions with Others</h3>     <p>     You are solely responsible for your interactions with other Users. Aigo may limit the number of connections you may have to other Users and may, in certain circumstances, prohibit you from contacting other Users through use of the Services or otherwise limit your use of the Services. Aigo reserves the right, but has no obligation, to monitor disputes between you and other members and to restrict, suspend, delete or close your account if Aigo determines, in our sole discretion, that doing so is necessary to enforce this Agreement.     </p>     </li>     <li>     <h3>15. DISCLAIMER.</h3>     <p>     SOME COUNTRIES AND JURISDICTIONS DO NOT ALLOW THE DISCLAIMER OF IMPLIED TERMS IN CONTRACTS WITH CONSUMERS AND AS A RESULT THE CONTENTS OF THIS SECTION MAY NOT APPLY TO YOU.     </p>     <p>     DO NOT RELY ON Aigo, ANY INFORMATION THEREIN, OR ITS CONTINUATION. WE PROVIDE THE PLATFORM FOR Aigo AND ALL INFORMATION AND SERVICES ON AN “AS IS” AND “AS AVAILABLE” BASIS. Aigo DOES NOT CONTROL OR VET USER GENERATED CONTENT FOR ACCURACY. WE DO NOT PROVIDE ANY EXPRESS WARRANTIES OR REPRESENTATIONS.     </p>     <p>     TO THE FULLEST EXTENT PERMISSIBLE UNDER APPLICABLE LAW, WE DISCLAIM ANY AND ALL IMPLIED WARRANTIES AND REPRESENTATIONS, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, ACCURACY OF DATA, AND NONINFRINGEMENT. IF YOU ARE DISSATISFIED OR HARMED BY Aigo OR ANYTHING RELATED TO Aigo, YOU MAY CLOSE YOUR Aigo ACCOUNT AND TERMINATE THIS AGREEMENT IN ACCORDANCE WITH SECTION 7 (“TERMINATION”) AND SUCH TERMINATION SHALL BE YOUR SOLE AND EXCLUSIVE REMEDY.     </p>     <p>     Aigo IS NOT RESPONSIBLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES FOR THE DELIVERY OF ANY MESSAGES SENT THROUGH Aigo TO ANYONE. IN ADDITION, WE NEITHER WARRANT NOR REPRESENT THAT YOUR USE OF THE SERVICE WILL NOT INFRINGE THE RIGHTS OF THIRD PARTIES. ANY MATERIAL, SERVICE, OR TECHNOLOGY DESCRIBED OR USED ON THE WEBSITE MAY BE SUBJECT TO INTELLECTUAL PROPERTY RIGHTS OWNED BY THIRD PARTIES WHO HAVE LICENSED SUCH MATERIAL, SERVICE, OR TECHNOLOGY TO US.     </p>     <p>     Aigo DOES NOT HAVE ANY OBLIGATION TO VERIFY THE IDENTITY OF THE PERSONS SUBSCRIBING TO ITS SERVICES, NOR DOES IT HAVE ANY OBLIGATION TO MONITOR THE USE OF ITS SERVICES BY OTHER USERS OF THE COMMUNITY; THEREFORE, Aigo DISCLAIMS ALL LIABILITY FOR IDENTITY THEFT OR ANY OTHER MISUSE OF YOUR IDENTITY OR INFORMATION.     </p>     <p>     Aigo DOES NOT GUARANTEE THAT THE SERVICES IT PROVIDES WILL FUNCTION WITHOUT INTERRUPTION OR ERRORS IN FUNCTIONING. IN PARTICULAR, THE OPERATION OF THE SERVICES MAY BE INTERRUPTED DUE TO MAINTENANCE, UPDATES, OR SYSTEM OR NETWORK FAILURES. Aigo DISCLAIMS ALL LIABILITY FOR DAMAGES CAUSED BY ANY SUCH INTERRUPTION OR ERRORS IN FUNCTIONING. FURTHERMORE, Aigo DISCLAIMS ALL LIABILITY FOR ANY MALFUNCTIONING, IMPOSSIBILITY OF ACCESS, OR POOR USE CONDITIONS OF THE Aigo SITE DUE TO INAPPROPRIATE EQUIPMENT, DISTURBANCES RELATED TO INTERNET SERVICE PROVIDERS, TO THE SATURATION OF THE INTERNET NETWORK, AND FOR ANY OTHER REASON.     </p>       </li>     <li>     <h3>16. TERMINATION.</h3>     <p>     You may terminate this Agreement, for any or no reason, at any time, by deleting your account and responding “yes” to confirm such action.     </p>     <p>     Aigo may terminate the Agreement and your account for any reason or no reason, at any time, with or without notice. This cancellation shall be effective immediately by electronic notification that your account will be deleted.     </p>     <p>     Aigo may restrict, suspend or terminate the account of any User who abuses or misuses the Services. Misuse of the Services includes abusing the Aigo messaging services; creating false profiles; infringing any intellectual property rights, violating any of the Do’s and Don’ts listed in Section 20, or any other behavior that Aigo, in its sole discretion, deems contrary to its purpose.     </p>          </li>     <li>     <h3>17. DISPUTE RESOLUTION</h3>     <p>This Agreement or any claim, cause of action or dispute (“claim”) arising out of or related to this Agreement shall be governed by the laws of the state of Georgia regardless of your country of origin or where you access Aigo, and notwithstanding of any conflicts of law principles. You and Aigo agree that all claims arising out of or related to this Agreement must be resolved exclusively by a state or federal court located in Cobb County, Georgia except as otherwise agreed by the parties or as described in the Arbitration Option paragraph below. You and Aigo agree to submit to the personal jurisdiction of the courts located within Cobb County, Georgia for the purpose of litigating all such claims. Notwithstanding the above, you agree that Aigo shall still be allowed to apply for injunctive remedies (or an equivalent type of urgent legal relief) in any jurisdiction. </p>     </li>     <li>     <h3>18. ARBITRATION</h3>     <p>     For any claim (excluding claims for injunctive or other equitable relief) where the total amount of the award sought is less than $10,000, the party requesting relief may elect to resolve the dispute in a cost effective manner through binding non-appearance-based arbitration. In the event a party elects arbitration, they shall initiate such arbitration through an established alternative dispute resolution (“ADR”) provider mutually agreed upon by the parties. The ADR provider and the parties must comply with the following rules: (a) the arbitration shall be conducted by telephone, online and/or be solely based on written submissions, the specific manner shall be chosen by the party initiating the arbitration; (b) the arbitration shall not involve any personal appearance by the parties or witnesses unless otherwise mutually agreed by the parties; and (c) any judgment on the award rendered by the arbitrator shall be final and may be entered in any court of competent jurisdiction.     </p>     </li>     <li>     <h3>19. For legal notices you may contact us at:</h3>     <p>     <b>Aigo, Inc.</b> <br>                                     ATTN: Legal <br>     2839 aces Ferry Road, Suite 1100<br>     Atlanta, GA 30339 <br>     USA <br>          </p>     </li>     <li>     <h3> 20. Entire Agreement.</h3>     <p>     You agree that this Agreement constitutes the entire, complete and exclusive agreement between you and Aigo regarding its application and services and supersedes all prior agreements and understandings, whether written or oral, or whether established by custom, practice, policy or precedent, with respect to the subject matter of this Agreement. You also acknowledge that you may be subject to additional terms and conditions that may apply when you use third-party content or third party software.     </p>     </li>     <li>     <h3>21. Amendments </h3>     <p>     We reserve the right to modify, supplement or replace the terms of the Agreement, effective upon electronic communication, via our mobile application or by posting at www.Aigo.com or notifying you otherwise.     </p>     <p>     No informal waivers, agreements or representations. Our failure to act with respect to a breach of this Agreement by you or others does not waive our right to act with respect to that breach or subsequent similar or other breaches. Except as expressly and specifically contemplated by the Agreement, no representations, statements, consents, waivers or other acts or omissions by any Aigo Affiliate shall be deemed legally binding on any Aigo Affiliate, unless documented in a physical writing hand signed by a duly appointed officer of Aigo.     </p>     <p>     No Injunctive Relief.  In no event shall you seek or be entitled to rescission, injunctive or other equitable relief, or to enjoin or restrain the operation of the Service, exploitation of any advertising or other materials issued in connection therewith, or exploitation of the Services or any content or other material used or displayed through the Services.     </p>     </li>     <li>     <h3>22. Aigo USER “DOS” and “DON’TS.”</h3>     <p>     As a condition to access Aigo, you agree to this Agreement and to strictly adhere to the following     </p>     <h4> DO:</h4>     <ul class=\"circle-buidlet\">     <li>•	Comply with all applicable laws, including, without limitation, privacy laws, intellectual property laws, export control laws, tax laws, and regulatory requirements;</li>     <li>•	Be cautious when providing your information to others (Kards, Konnect, Trade)</li>     <li>•	Protect your sensitive personal information</li>     <li>•	Provide accurate information to us and update it as necessary;</li>     <li>•	Review and comply with our Privacy Policy;</li>     <li>•	Review and comply with notices sent by Aigo concerning the Services; and</li>     <li>•	Use the Services in a polite and professional manner.</li>     </ul>     <h4>DON’T:</h4>     <ul class=\"circle-buidlet\">     <li>•	Act dishonestly or unprofessionally by engaging in unprofessional behavior by posting inappropriate, inaccurate, or objectionable content to Aigo;</li>     <li>•	Publish inaccurate information in the designated fields on the profile form </li>     <li>•	Create a false identity on Aigo;</li>     <li>•	Falsely state, impersonate or otherwise misrepresents your identity</li>     <li>•	Use language or upload photos that are unlawful, libelous, abusive, obscene, discriminatory or otherwise objectionable;</li>     <li>•	Include information that you do not have the right to disclose or make available under any law or under contractual or fiduciary relationships</li>     <li>•	Infringe upon patents, trademarks, trade secrets, copyrights or other proprietary rights;</li>     <li>•	Duplicate, license, sublicense, publish, broadcast, transmit, distribute, perform, display, sell, rebrand, or otherwise transfer information found on Aigo (excluding content posted by you) except as permitted in this Agreement, Aigo’s developer terms and policies, or as expressly authorized by Aigo;</li>     <li>•	Reverse engineer, decompile, disassemble, decipher or otherwise attempt to derive the source code for any underlying intellectual property used to provide the Services, or any part thereof</li>     <li>•	Utilize or copy information, content or any data you view on and/or obtain from Aigo to provide any service that is competitive, in Aigo’s sole discretion, with Aigo;</li>     <li>•	Adapt, modify or create derivative works based on Aigo or technology underlying the Services, or other Users’ content, in whole or part, except as permitted under Aigo’s developer program;</li>     <li>•	Infringe or use Aigo’s brand, logos and/or trademarks, including, without limitation, using the word “Aigo” in any business name, email, or URL or including Aigo’s trademarks and logos except as provided in the Brand Guidelines or as expressly permitted by Aigo</li>     </ul>     </li>          </ul>     </div> </body></html>" baseURL:nil];
    
    // add to view
    [self.view addSubview:self.termsView];
    CGRect rect = CGRectMake(0, HEIGHT_IPHONE, WIDTH_IPHONE, HEIGHT_IPHONE - HEIGHT_STATUS_BAR);
    self.termsView.frame = rect;
    rect.origin.y = 0;
    [UIView animateWithDuration:0.3f animations:^{
        self.termsView.frame = rect;
    }];
}

- (IBAction)saveTouchUpInside:(UIButton *)sender {
    // MinhPB 2012/12/04
    if (![_textFieldUsername.text isAvailableWithCheckingType:enumNSStringExtrasCheckingType_Register_UserName]) {
        [_textFieldUsername becomeFirstResponder];
        return;
    }
    if (![_textFieldPassword.text isAvailableWithCheckingType:enumNSStringExtrasCheckingType_Register_Password]) {
        [_textFieldPassword becomeFirstResponder];
        return;
    }
    if (![_textFieldEmail.text isAvailableWithCheckingType:enumNSStringExtrasCheckingType_Register_Email]) {
        [_textFieldEmail becomeFirstResponder];
        return;
    }
    if (![_textFieldFirstName.text isAvailableWithCheckingType:enumNSStringExtrasCheckingType_Register_FirstName]) {
        [_textFieldFirstName becomeFirstResponder];
        return;
    }
    if (![_textFieldLastName.text isAvailableWithCheckingType:enumNSStringExtrasCheckingType_Register_LastName]) {
        [_textFieldLastName becomeFirstResponder];
        return;
    }
    
    [self requestDataWithType:ENUM_API_REQUEST_TYPE_USER_REGISTER];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    // MinhPB 2012/11/20
    if (textField != _textFieldLastName) {
        textField.returnKeyType = UIReturnKeyNext;
    }
    else {
        textField.returnKeyType = UIReturnKeyDone;
    }
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == _textFieldUsername) {
        [_textFieldPassword becomeFirstResponder];
    }
    else if (textField == _textFieldPassword) {
        [_textFieldEmail becomeFirstResponder];
    }
    else if (textField == _textFieldEmail) {
        [_textFieldFirstName becomeFirstResponder];
    }
    else if (textField == _textFieldFirstName) {
        [_textFieldLastName becomeFirstResponder];
    }
    else {
        [self hideKeyboard];
    }
    
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (textField == _textFieldEmail) {
        _scrollViewMainView.contentOffset = CGPointMake(0, _textFieldEmail.frame.size.height);
    }
    else if (textField == _textFieldFirstName) {
        _scrollViewMainView.contentOffset = CGPointMake(0, _textFieldEmail.frame.size.height*2);
    }
    else if (textField == _textFieldLastName) {
        _scrollViewMainView.contentOffset = CGPointMake(0, _textFieldEmail.frame.size.height*3);
    }
    else {
        _scrollViewMainView.contentOffset = CGPointMake(0, 0);
    }
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
}

- (void)alertView:(NSString *)title withMessage:(NSString *)message withDismissButton:(NSString *)dismissString{
    UIAlertView *_alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:dismissString otherButtonTitles:nil];
    [_alert show];
}

- (void)hideKeyboard {
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    _scrollViewMainView.contentOffset = CGPointMake(0, 0);
}

#pragma mark - API Request
- (void)requestDataWithType:(ENUM_API_REQUEST_TYPE)type
{
    if (type == ENUM_API_REQUEST_TYPE_USER_REGISTER) {
        NSString *userType = @"";
        
#ifdef __CLIENT__
        userType = STRING_REQUEST_KEY_CLIENT;
#else
        userType = STRING_REQUEST_KEY_DRIVER;
#endif
        
        NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:@"%@ %@", _textFieldFirstName.text, _textFieldLastName.text], _textFieldEmail.text, _textFieldUsername.text, _textFieldPassword.text, @"", userType, [AppViewController Shared].configDataModel.deviceToken, nil] forKeys:[NSArray arrayWithObjects:STRING_REQUEST_KEY_NAME, STRING_REQUEST_KEY_EMAIL, STRING_REQUEST_KEY_USER, STRING_REQUEST_KEY_PASS, STRING_REQUEST_KEY_COUNTRY, STRING_REQUEST_KEY_USER_TYPE, STRING_REQUEST_KEY_DEVICE_TOKEN, nil]];
        [_APIRequester requestWithType:type andRootURL:STRING_REQUEST_URL_REGISTRY_ACCOUNT andPostMethodKind:YES andParams:userInfo andDelegate:self];
    }
    if (type == ENUM_API_REQUEST_TYPE_USER_RECOVER_PASSWORD) {
        NSMutableDictionary *_param = [NSMutableDictionary dictionaryWithObjectsAndKeys:_textFieldEmail.text, STRING_REQUEST_KEY_EMAIL, nil];
        [_APIRequester requestWithType:type andRootURL:STRING_REQUEST_URL_USER_RECOVERY_PASSWORD andPostMethodKind:YES andParams:_param andDelegate:self];
    }
    [[AppViewController Shared] isRequesting:YES andRequestType:type andFrame:FRAME(0, 0, WIDTH_IPHONE, HEIGHT_IPHONE)];
}

- (void)requestFailed:(ASIHTTPRequest *)request andType:(ENUM_API_REQUEST_TYPE)type
{
    NSLog(@" requestFailed %@ ", request.responseString);
    
    [[AppViewController Shared] isRequesting:NO andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:CGRectZero];
    
    ALERT(STRING_ALERT_TITLE_SORRY, STRING_ALERT_CONNECTION_ERROR);
}

- (void)requestFinished:(ASIHTTPRequest *)request andType:(ENUM_API_REQUEST_TYPE)type
{
    NSLog(@"requestFinished %@, request.responseStatusCode: %i", request.responseString, request.responseStatusCode);
    
    [[AppViewController Shared] isRequesting:NO andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:CGRectZero];
    
    NSError *error;
    SBJSON *sbJSON = [SBJSON new];
    
    if (![sbJSON objectWithString:[request responseString] error:&error] || request.responseStatusCode != 200 || !request) {
//        if (![ASIHTTPRequest isNetworkReachable]) {
//            ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_SERVER_ERROR);
//        }
        ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, [[sbJSON objectWithString:[request responseString] error:&error] objectForKey:STRING_RESPONSE_KEY_MSG]);
        return;
    }
    
    NSMutableArray *jsonData = [sbJSON objectWithString:[request responseString] error:&error];
    if (type == ENUM_API_REQUEST_TYPE_USER_REGISTER) {
        if (jsonData.count > 0) {
            NSMutableDictionary *dicJson = [jsonData objectAtIndex:0];
            
            [[UserDataManager Shared] resetAllData];// MinhPB 2012/07/09
            
            [UserDataManager Shared].userID = [dicJson objectForKey:STRING_RESPONSE_KEY__ID];
            [UserDataManager Shared].userName = _textFieldUsername.text;
            [UserDataManager Shared].accessToken = @"";
            [UserDataManager Shared].password = _textFieldPassword.text;
            [UserDataManager Shared].sessionID = [dicJson objectForKey:STRING_RESPONSE_KEY__ID];
            [UserDataManager Shared].isLoginWith_FB_TW = NO;
            [UserDataManager Shared].avatarSmallURL = @"";
            [UserDataManager Shared].loginStatus = YES;
            [[UserDataManager Shared] save];
            
            // MinhPB 2012/12/26
            [[AppViewController Shared] isRequesting:YES andRequestType:ENUM_API_REQUEST_TYPE_USER_LOGIN andFrame:FRAME(0, 0, [SupportFunction getDeviceWidth], [SupportFunction getDeviceHeight]-HEIGHT_STATUS_BAR)];
            
            [[AutomationDataManager Shared] reloadAllDataWithDataIsReady:enumAutomationDataIsReady_ForHome_BeforeEntering andDelegate:self];
//            [[AppViewController Shared] changeToHomeFromWelcomeScreen:YES];
        }
    }
    if (type ==  ENUM_API_REQUEST_TYPE_USER_RECOVER_PASSWORD) {
//        if ([[jsonData objectForKey:STRING_REQUEST_KEY_MESSAGE] isEqualToString:STRING_RESPONSE_CODE_SUCCESS]) {
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:STRING_ALERT_RECOVERY_PASSWORD_SUCCESS delegate:nil cancelButtonTitle:STRING_ALERT_OK otherButtonTitles:nil, nil];
//            [alert show];
//        }
//        else
//            ALERT(STRING_ALERT_TITLE_SORRY, STRING_ALERT_RECOVERY_PASSWORD_EMAIL_INVALID);
    }
    
}

#pragma mark - AutomationDataManagerProtocol
- (void)didRequestFinishedWithDataIsReady:(enumAutomationDataIsReady)isReady {
    if (isReady == enumAutomationDataIsReady_ForHome_BeforeEntering) {
        [[AppViewController Shared] isRequesting:NO andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:CGRectZero];
        [[AppViewController Shared] changeToHomeFromWelcomeScreen:YES];
    }
}

- (void)didRequestFailedWithDataIsReady:(enumAutomationDataIsReady)isReady {
    if (isReady == enumAutomationDataIsReady_ForHome_BeforeEntering) {
        [[AppViewController Shared] isRequesting:NO andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:CGRectZero];
        [UserDataManager Shared].loginStatus = NO;
    }
}

@end
